import { Component, OnInit, Input } from '@angular/core';

import { ModalController } from '@ionic/angular';
import { ValueAccessor } from '@ionic/angular/dist/directives/control-value-accessors/value-accessor';

import { AppGlobalService } from 'src/app/shared/service/app-global.service';

import { isNullOrUndefined } from 'util';

import { max } from 'rxjs/operators';

@Component({
  selector: 'app-modal-of-select',
  templateUrl: './modal-of-select.component.html',
  styleUrls: ['./modal-of-select.component.scss'],
})
export class ModalOfSelectComponent implements OnInit {

  @Input() tagData: any;
  tempData: any;
  checkAll: any;
  constructor(
    public modalController: ModalController,
    public ppGlobalService: AppGlobalService,

  ) { }

  ngOnInit() {
    this.tempData = JSON.parse(JSON.stringify(this.tagData));
    this.checkAll = false;
    if (!isNullOrUndefined(this.tempData.value)) {

      let valueArray: any;
      if (Array.isArray(this.tempData.value)) {
        valueArray = this.tempData.value;
      } else {
        valueArray = this.tempData.value.split(',');
      }
      let count = 0;
      this.tempData.data.forEach(element => {
        if (valueArray.indexOf(element.value) > -1) {
          element.check = true;
          count += 1;
        }
      });
      if (count === this.tempData.data.length) {
        this.checkAll = true;
      }
    }
  }
  changeItem(item) {

    item.check = !item.check;
    if (item.check &&  item.radio) {
      // 单选
      this.tempData.data.forEach(element => {
        if (element !== item) {
          element.check = false;
        }
      });
    } else
    if (this.tempData.max === 1) {
      // 单选
      this.tempData.data.forEach(element => {
        if (element !== item) {
          element.check = false;
        }
      });
    } else if (this.tempData.max) {
      let count = 0;
      this.tempData.data.forEach(element => {
        if (element.check) {
          count += 1;
        }
      });
      if (count > this.tempData.max) {
        item.check = !item.check;
        this.ppGlobalService.showToast('最多选' + this.tempData.max + '个', 1500, "middle");
        this.checkAll = false;
      } else if (count === this.tempData.data.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    } else {
      let count = 0;
      this.tempData.data.forEach(element => {
        if (element.radio) {
          element.check = false;
        } 
        if (element.check) {
          count += 1;
        }
      });
      if (count === this.tempData.data.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    }
  }
  checkAllItem() {
    this.checkAll = !this.checkAll;
    this.tempData.data.forEach(element => {
      if (this.checkAll) {
        element.check = true;
      } else {
        element.check = false;
      }
    });
  }
  check() {
    this.modalController.dismiss({ data: this.tempData });
  }
}
